<template>
  <div class="product-detail">
    <header class="detail-nav">
      <i class="iconfont iconfont-31fanhui1" @click="$router.go(-1)"></i>
      <div class="nav-list">
        <span :class="{ active: num == 0 }" @click="changenum(0)">
          <van-icon name="location-o" color="red" v-show="num == 0" />商品
        </span>
        <span :class="{ active: num == 1 }" @click="changenum(1)">
          <van-icon name="location-o" color="red" v-show="num == 1" />商品详情
        </span>
        <span :class="{ active: num == 2 }" @click="changenum(2)">
          <van-icon name="location-o" color="red" v-show="num == 2" />商品推荐
        </span>
      </div>
      <i class="iconfont iconfont-gengduo"></i>
    </header>
    <section class="product-focus">
      <van-swipe
        :autoplay="3000"
        indicator-color="white"
        class="swiper-container"
      >
        <van-swipe-item v-for="(item, index) in imgUrls" :key="index">
          <img :src="item" class="swiper_img" alt="" />
        </van-swipe-item>
      </van-swipe>
    </section>
    <section class="detail-info">
      <p class="detail-info-name">
        {{ data.name }}
      </p>
      <p class="detail-info-subtitle">{{ data.subtitle }}</p>
      <div>
        <span class="detail-info-price">￥{{ data.price }}</span>
        <span class="detail-info-stock">库存{{ data.stock }}件</span>
      </div>
    </section>
    <section class="detail-content" ref="detailContent" id="content">
      <p class="detail-gap"></p>
      <ul>
        <li>概述</li>
        <li>参数</li>
        <li>安装服务</li>
        <li>常见问题</li>
      </ul>
      <div v-html="data.detail" class="detailimg"></div>
    </section>
    <van-goods-action>
      <van-goods-action-icon icon="chat-o" text="客服" color="#ee0a24" />
      <van-goods-action-icon icon="cart-o" text="购物车" />
      <van-goods-action-button
        type="warning"
        text="加入购物车"
        @click="handShopCart"
      />
      <van-goods-action-button type="danger" text="立即购买" />
    </van-goods-action>

    <van-sku
      v-model="show"
      :sku="sku"
      :goods="goods"
      :goods-id="goodsId"
      :hide-stock="sku.hide_stock"
      @buy-clicked="onBuyClicked"
      @add-cart="onAddCartClicked"
    />
  </div>
</template>

<script>
import { getDetail, carAdd } from "../../api/index";


export default {
  data() {
    return {
      num: 0,
      imgUrls: [],
      data: [],
      show: false,
      sku: {
        // 所有sku规格类目与其值的从属关系，比如商品有颜色和尺码两大类规格，颜色下面又有红色和蓝色两个规格值。
        // 可以理解为一个商品可以有多个规格类目，一个规格类目下可以有多个规格值。
        tree: [
          {
            k: "颜色", // skuKeyName：规格类目名称
            k_s: "s1", // skuKeyStr：sku 组合列表（下方 list）中当前类目对应的 key 值，value 值会是从属于当前类目的一个规格值 id
            v: [
              {
                id: "1", // skuValueId：规格值 id
                name: "红色", // skuValueName：规格值名称
                imgUrl: "https://img01.yzcdn.cn/1.jpg", // 规格类目图片，只有第一个规格类目可以定义图片
                previewImgUrl: "https://img01.yzcdn.cn/1p.jpg", // 用于预览显示的规格类目图片
              },
              {
                id: "1",
                name: "蓝色",
                imgUrl: "https://img01.yzcdn.cn/2.jpg",
                previewImgUrl: "https://img01.yzcdn.cn/2p.jpg",
              },
            ],
            largeImageMode: true, //  是否展示大图模式
          },
        ],
        // 所有 sku 的组合列表，比如红色、M 码为一个 sku 组合，红色、S 码为另一个组合
        list: [
          {
            id: 2259, // skuId
            s1: "1", // 规格类目 k_s 为 s1 的对应规格值 id
            s2: "1", // 规格类目 k_s 为 s2 的对应规格值 id
            price: 100, // 价格（单位分）
            stock_num: 110, // 当前 sku 组合对应的库存
          },
        ],
        price: "1.00", // 默认价格（单位元）
        stock_num: 227, // 商品总库存
        collection_id: 2261, // 无规格商品 skuId 取 collection_id，否则取所选 sku 组合对应的 id
        none_sku: false, // 是否无规格商品
        hide_stock: false, // 是否隐藏剩余库存
      },
      goods: {
        // 默认商品 sku 缩略图
        picture: "https://img01.yzcdn.cn/1.jpg",
      },
      goodsId: 2261,
    };
  },
  methods: {
    changenum(i) {
      this.num = i;
      if (i == 0) {
        window.scrollTo(0, 0);
      } else if (i == 1) {
        this.$nextTick(() => {
          window.scrollTo(0, this.$refs["detailContent"].offsetTop - 50);
        });
      } else {
        window.scrollTo(0, 0);
      }
    },
    onBuyClicked() {
      console.log("购买东西");
    },
    onAddCartClicked(value) {
      console.log("加入购物车", value);
      const params = {
        productId: value.goodsId,
        count: value.selectedNum,
      };
      if (sessionStorage.getItem("isLogin")) {
        carAdd(params, (res) => {
          console.log(res);
          this.$store.dispatch("getcars")
          this.$router.push("/shopcart")
        });
      }else{
        this.$router.push("/login")
      }
    },
    handShopCart() {
      this.show = true;
      this.goods.picture = this.imgUrls[0];
      // console.log(this.data);
      this.goodsId = this.data.id;
      // console.log(this.goodsId);
    },
    setSku(detailInfo, tempList) {
      //  组装 SKU 数据
      //  sku 规格 和 商品
      let tempTreeV = [];
      this.sku.list = [];
      for (let index = 0; index < 2; index++) {
        // 组装 suk.tree[0].v
        let obj = {
          id: index + 1, // skuValueId：规格值 id
          name: "红色", // skuValueName：规格值名称
          imgUrl: tempList[index], // 规格类目图片，只有第一个规格类目可以定义图片
          previewImgUrl: tempList[index], // 用于预览显示的规格类目图片
        };
        if (index === 1) {
          obj.name = "蓝色";
        }
        tempTreeV.push(obj);
        // 组装 sku.list
        let preItem = {
          id: detailInfo.id, // skuId
          s1: index + 1, // 规格类目 k_s 为 s1 的对应规格值 id
          price: detailInfo.price * 100, // 价格（单位分）
          stock_num: detailInfo.stock - 1, // 当前 sku 组合对应的库存
        };
        if (index === 1) {
          preItem.stock_num = 1;
        }
        this.sku.list.push(preItem);
      }
      this.sku.tree[0].v = tempTreeV;
      // 价格 和库存总数
      this.sku.price = detailInfo.price; // 默认价格（单位元）
      this.sku.stock_num = detailInfo.stock - 0; // 商品总库存

      // 商品展示的默认图
      this.goods.picture = tempList[0];
      //   设置 对应商品ID
      this.goodsId = detailInfo.id;
    },
  },

  created() {
    getDetail(Number(this.$route.params.id), (res) => {
      this.data = res.data.data;
      if(this.data.subImages){
        this.imgUrls = this.data.subImages
        .split(",")
        .map((el) => this.data.imageHost + el);
      }else{
        this.imgUrls = [this.data.imageHost+this.data.mainImage,this.data.imageHost+this.data.mainImage]
      }
      this.setSku(this.data, this.imgUrls);
    });
  },
};
</script>

<style lang="scss" scoped>
.product-detail {
  width: 100%;

  .detail-nav {
    // @include fj;
    display: flex;
    justify-content: space-between;
    position: fixed;
    left: 0;
    top: 0;
    width: 100%;
    height: 88px;
    padding: 0 20px;
    line-height: 88px;
    box-sizing: border-box;
    z-index: 1000;
    color: #252525;
    background: #fff;
    border-bottom: 1px solid #dcdcdc;

    i {
      font-size: 50px;
      color: #000;
    }

    div span {
      padding: 0 20px;
      font-size: 28px;

      &.active {
        color: red;
      }

      .iconfont {
        padding-right: 8px;
        font-size: 28px;
        color: red;
      }
    }
  }

  .product-focus {
    margin-top: 88px;

    .swiper-container {
      .swiper_img {
        width: 100%;
        height: 700px;
      }
    }
  }

  .detail-info {
    width: 100%;
    padding: 20px 30px;
    font-size: 30px;
    box-sizing: border-box;

    .detail-info-name {
      font-size: 40px;
      color: #333;
    }

    .detail-info-subtitle {
      padding: 10px 0;
      font-size: 28px;
      color: #999;
    }

    div {
      // @include fj;
      display: flex;
      justify-content: space-between;
      height: 70px;
      line-height: 80px;
      padding: 10px 0;
      font-size: 32px;
      color: #999;

      .detail-info-price {
        color: red;
        font-size: 44px;
      }
    }
  }

  .detail-content {
    width: 100%;

    .detail-gap {
      width: 100%;
      height: 20px;
      background: #eee;
    }

    ul {
      // @include fj;
      display: flex;
      justify-content: space-between;
      width: 100%;
      margin: 20px 0;

      li {
        flex: 1;
        padding: 10px 0;
        text-align: center;
        font-size: 30px;
        border-right: 1px solid #999;
        box-sizing: border-box;

        &:last-child {
          border-right: none;
        }
      }
    }
  }
}
</style>
<style lang="scss">
.detailimg {
  width: 100%;
  overflow: hidden;

  p {
    width: 100%;
    font-size: 40px;
    text-align: center;
  }

  img {
    width: 100%;
    height: 100%;
  }
}
</style>